import axios from 'axios'
import '@/libs/utils'
import '@/libs/jquery-vender.js'
import layer from 'layui-layer'

let fetch = {}

const service = axios.create({
  timeout: 30000
})

// request拦截器
service.interceptors.request.use(config => {
  config.headers['Authorization'] = utils.getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
})

// respone拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.log('error:' + error)
    return Promise.reject(error)
  }
)

fetch.get = function (url, data, callback, errorHandler) {
  // ajax(url, data, 'GET', callback, errorHandler)
  let loading = layer.load(2)
  service({
    url: url,
    method: 'get',
    data: data,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }]
  })
    .then(function (response) {
      layer.close(loading)
      if (callback) {
        callback(response.data)
      }
    })
    .catch(function (error) {
      layer.close(loading)
      if (errorHandler) {
        errorHandler(error.data)
      } else {
        console.log(error)
      }
    })
}

fetch.post = function (url, data, callback, errorHandler) {
  let loading = layer.load(2)
  service({
    url: url,
    method: 'post',
    data: data,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }]
  })
    .then(function (response) {
      layer.close(loading)
      if (callback && response && response.data) {
        callback(response.data)
      }
    })
    .catch(function (error) {
      layer.close(loading)
      if (errorHandler) {
        errorHandler(error.data)
      } else {
        console.log(error)
      }
    })
}

export default fetch
